
package com.eltonkent.ui;

import java.util.Date;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.eltonkent.R;
import com.eltonkent.db.CredentialTable;
import com.eltonkent.util.DateUtil;
import com.eltonkent.util.StringUtil;

public final class LoginActivity extends ParentActivity
{

	boolean isFirstTime;
	private static final int DIALOG_DISCLAIMER = 95;

	private boolean isFirstTime()
	{
		SharedPreferences preferences = getApplicationPreferences();
		if(!preferences.contains(ApplicationConstants.PREF_FIRST_TIME))
		{
			return true;
		}
		return false;
	}

	@Override
	protected void populateUI()
	{
		setToPath(getResources().getString(isFirstTime ? R.string.login_new : R.string.login));
		String lastLogin = CredentialTable.lastLogin;
		if(lastLogin != null)
		{
			lastLogin = getResources().getString(R.string.last_logon_at) + lastLogin;
			setStatusText(lastLogin);
		}
		showExitButton();

		// byte[] clearText =
		// "www.java2s.comdfgdfgdfgfdgfdgdfgdfgvcbcvbvcbvbdsfdsfsdfdsfdsfxc vcxvcxvcxvxcvcxvcxvcxv fgdfgdfdfgdgdfgdfgdfgfdgdfgdfgdfgdfgdfgdfgdfgdfgdfgdfgdfgerretertertertretretertreterter"
		// .getBytes();

		// SecretKey key = null;
		// try {
		// key = KeyGenerator.getInstance("DES").generateKey();
		// } catch (NoSuchAlgorithmException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// // for CBC; must be 8 bytes
		// byte[] initVector = new byte[] { 0x10, 0x10, 0x01, 0x04, 0x01, 0x01,
		// 0x01, 0x02 };
		//
		// AlgorithmParameterSpec algParamSpec = new
		// IvParameterSpec(initVector);
		// Cipher m_encrypter = null;
		// try {
		// m_encrypter = Cipher.getInstance("DES/CBC/PKCS5Padding");
		// } catch (NoSuchAlgorithmException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (NoSuchPaddingException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// Cipher m_decrypter = null;
		// try {
		// m_decrypter = Cipher.getInstance("DES/CBC/PKCS5Padding");
		// } catch (NoSuchAlgorithmException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (NoSuchPaddingException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// try {
		// m_encrypter.init(Cipher.ENCRYPT_MODE, key, algParamSpec);
		// } catch (InvalidKeyException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (InvalidAlgorithmParameterException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// try {
		// m_decrypter.init(Cipher.DECRYPT_MODE, key, algParamSpec);
		// } catch (InvalidKeyException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (InvalidAlgorithmParameterException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// byte[] encryptedText = null;
		// try {
		// encryptedText = m_encrypter.doFinal(clearText);
		// } catch (IllegalBlockSizeException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (BadPaddingException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// byte[] decryptedText = null;
		// try {
		// decryptedText = m_decrypter.doFinal(encryptedText);
		// } catch (IllegalBlockSizeException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (BadPaddingException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// System.out.println(new String(clearText));
		// System.out.println("enc" + new String(encryptedText));
		// System.out.println("dec" + new String(decryptedText));
		// System.out.println("plain length" + clearText.length);
		// System.out.println("enc length" + encryptedText.length);

		// BFEncryptionEngine enc = BFEncryptionEngine.getInstance();
		// byte[] encryptedText = enc.encrypt(clearText);
		// byte[] decryptedText = enc.decrypt(encryptedText);
		//
		// System.out.println(new String(clearText));
		// System.out.println("enc" + new String(encryptedText));
		// System.out.println("dec" + new String(decryptedText));
		// System.out.println("plain length" + clearText.length);
		// System.out.println("enc length" + encryptedText.length);
	}

	private void resetPreference()
	{
		SharedPreferences pref = getApplicationPreferences();
		SharedPreferences.Editor editor = pref.edit();
		editor.remove(ApplicationConstants.PREF_FIRST_TIME);
		editor.remove(ApplicationConstants.PREF_SAVED_DATE);
		editor.commit();

	}

	private void setFirstTimePreference(String password)
	{
		String dateAdded = DateUtil.getFormattedDate(new Date(System.currentTimeMillis()));

		CredentialTable table = new CredentialTable(LoginActivity.this);
		table.savePassword(password, dateAdded);
		SharedPreferences preferences = getApplicationPreferences();
		SharedPreferences.Editor editor = preferences.edit();
		editor.putBoolean(ApplicationConstants.PREF_FIRST_TIME, false);
		editor.putString(ApplicationConstants.PREF_SAVED_DATE, dateAdded);
		editor.commit();
	}

	/** Called when the activity is first created. */
	@Override
	public void setupUI(Bundle savedInstanceState)
	{
		CredentialTable passwordTbl = new CredentialTable(LoginActivity.this);
		final String pass = passwordTbl.getPassword();
		if(pass == null)
		{
			resetPreference();
		}
		isFirstTime = isFirstTime();
		if(!isFirstTime)
		{
			useLoginScreen(pass);
		} else
		{
			usePasswordSetupScreen();
		}
	}

	private void showFolderListScreen()
	{
		hideProgress();
		Intent folderScreen = new Intent(LoginActivity.this, FolderListActivity.class);
		startActivity(folderScreen);
		finish();
	}

	private void useLoginScreen(final String pass)
	{
		setContentView(R.layout.activity_login);
		setToPath(getResources().getString(R.string.login));
		Button btn = (Button) findViewById(R.id.btnLogin);
		TextView txtPassword = (TextView) findViewById(R.id.passwordText);
		SharedPreferences prefs = getApplicationPreferences();
		txtPassword.setTextSize(prefs.getInt(ApplicationConstants.PREF_TEXT_SIZE,
				ApplicationConstants.PREF_DEF_TEXTSIZE));
		final EditText password = (EditText) findViewById(R.id.password);
		if(TextUtils.isDigitsOnly(pass))
		{
			password.setRawInputType(InputType.TYPE_CLASS_NUMBER);
		}
		final Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		btn.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{

				// GMailPostMan postman = new
				// GMailPostMan("eltonkent@gmail.com", "javarocks");
				// try
				// {
				// postman.sendMail("Test mail", "this. is the body",
				// "eltonkent@gmail.com",
				// "elton.kent@accenture.com");
				// } catch(Exception e)
				// {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }

				// List list = TemplateFactory.getTemplateList(
				// getApplicationContext(), R.xml.finance);
				// Log.d("UI", "Template Container size" + list.size());

				// SafeTemplateFactory.getFieldContainer(getApplicationContext(),
				// R.xml.finance, "Visa Card");

				Log.d("UI", "Button clicked!");
				if(pass.equals(password.getText().toString()))
				{
					showProgress();
					CredentialTable table = new CredentialTable(getApplicationContext());
					table.updateLastLogin(getApplicationPreferences().getString(
							ApplicationConstants.PREF_SAVED_DATE, null), DateUtil
							.getFormattedDate(new Date(System.currentTimeMillis())));
					showFolderListScreen();
				} else
				{
					password.setText(null);
					password.startAnimation(shake);
					Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
					vibrator.vibrate(50);
					vibrator.vibrate(50);

				}
			}
		});

	}

	private void usePasswordSetupScreen()
	{
		setContentView(R.layout.activity_loginnewpassword);
		final EditText password = (EditText) findViewById(R.id.newPass);
		final EditText passwordRepeated = (EditText) findViewById(R.id.repeatPass);
		final TextView errorText = (TextView) findViewById(R.id.errorText);
		Button btn = (Button) findViewById(R.id.btnLogin);
		btn.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				String validate = StringUtil.validatePassword(getApplicationContext(), password.getText(),
						passwordRepeated.getText());
				if(validate.equals("OK"))
				{
					errorText.setVisibility(View.GONE);
					setFirstTimePreference(password.getText().toString());
					// showFolderListScreen();
					useLoginScreen(password.getText().toString());
				} else
				{
					errorText.setText(validate);
					errorText.setVisibility(View.VISIBLE);
				}
			}
		});
		boolean showDisclaimer = getApplicationPreferences().getBoolean(
				ApplicationConstants.PREF_IS_DISCLAIMER_SHOWN, true);
		if(showDisclaimer)
		{
			showDialog(DIALOG_DISCLAIMER);
		}
	}

	protected final Dialog onCreateDialog(int id)
	{
		switch(id)
		{
			case DIALOG_DISCLAIMER:
				return getDisclaimerDialog();
			default:
				return super.onCreateDialog(id);
		}
	}

	private Dialog getDisclaimerDialog()
	{
		final Dialog dialog = getCustomDialog(R.layout.dialog_disclaimer, R.string.disclaimer_title);
		dialog.setCancelable(false);
		Button[] okCancel = getOKCancelButtons(dialog);
		Button btnOk = okCancel[0];
		Button btnCancel = okCancel[1];
		btnCancel.setText(R.string.disagree);
		btnOk.setText(R.string.agree);
		btnOk.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				SharedPreferences.Editor edit = getApplicationPreferences().edit();
				edit.putBoolean(ApplicationConstants.PREF_IS_DISCLAIMER_SHOWN, false);
				edit.commit();
				dialog.dismiss();
			}
		});
		btnCancel.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				dialog.dismiss();
				System.exit(0);

			}
		});
		return dialog;
	}
}
